//
//  ZDBMyMessageViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/17.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBMyMessageViewController.h"
#import "ZDBMyMessageTableViewCell.h"
#import "ZDBMessage.h"

@interface ZDBMyMessageViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic,strong) NoNetworkView * workView;
@end

@implementation ZDBMyMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    WeakSelf
    // 上拉加载
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page =1;
        [weakSelf mailMsgList];
    }];
    [header beginRefreshing];
    self.tableView.mj_header = header;
    
    MJRefreshBackStateFooter * foot = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
         self.page ++;
         [weakSelf mailMsgList];
    }];
    self.tableView.mj_footer = foot;
}
#pragma 获取消息列表
- (void)mailMsgList
{
    WeakSelf
    NSString  * mailMsg = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"mailMsg"];
    [[SmileHttpTool sharedInstance] POST:mailMsg parameters:@{@"pageNum":@(self.page),@"pageSize":@(10)} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        NSDictionary * dic = responseObject;
        if (!kDictIsEmpty(dic)) {
            NSInteger  pages = [dic[@"pages"] integerValue];//一共多少条数据
            NSArray * list = dic[@"list"];//
            if (weakSelf.page>pages)
            {
                 [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else
            {
                if (weakSelf.page > 1)
                {
                    [weakSelf.dataSource addObjectsFromArray:[ZDBMessage mj_objectArrayWithKeyValuesArray:list]];
                    
                }else
                {
                    self.dataSource = [ZDBMessage mj_objectArrayWithKeyValuesArray:list];
                }
            }
            [weakSelf setMsgRead];
            [self.tableView reloadData];
        }else
        {
            
            [JMNotifyView showNotify:message isSuccessful:NO];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self placeholderViewWithFrame:self.tableView.frame NoNetwork:NO];
        });
    } failure:^(id responseObject, NSError *error) {
       [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
//已读消息
- (void)setMsgRead
{
    
    NSMutableString * msgMustr = [[NSMutableString alloc] init];
    for (ZDBMessage * message in self.dataSource)
    {
         [msgMustr appendString:kFormat(@"%@,", message.id)];
    }
    if (!kStringIsEmpty(msgMustr)) {
         NSRange deleteRange = {[msgMustr length] - 1, 1 };
        [msgMustr deleteCharactersInRange:deleteRange];
        NSString  * setMsgRead = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"setMsgRead"];
        [[SmileHttpTool sharedInstance] POST:setMsgRead parameters:@{@"ids":msgMustr} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
            
        
            
        } failure:^(id responseObject, NSError *error) {
            
        }];
    }
   
}
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight  - kStatusBarAndNavigationBarHeight)style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor =  VIEWBGCOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.0001)];
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBMyMessageTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBMyMessageTableViewCell"];
        
    
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBMessage * message = _dataSource[indexPath.row];
    
      NSData *data = [message.content dataUsingEncoding:NSUnicodeStringEncoding];
      NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
      NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
      [attr addAttribute:NSFontAttributeName value:AutoFont(14) range:NSMakeRange(0, attr.length)];
      CGSize attSize = [attr boundingRectWithSize:CGSizeMake(UIScreenWidth-30-16, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    if (attSize.height>48) {
        return 115-48+attSize.height;
    }
    return 115;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBMyMessageTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBMyMessageTableViewCell" forIndexPath:indexPath];
    cell.message = _dataSource[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.dataSource.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) NoNetwork:NoNetwork];
        [self.tableView addSubview:_workView];
        //_workView.centerY = self.collectionView.centerY-100;
    }else
    {
        [_workView dissmiss];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
